﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Tycho.Runtime;
using System.Threading;
using Tycho.Transactions;
using Tycho.Language;

namespace Tycho.Peyote {
    /// <summary>
    /// Interaction logic for InteractivePrompt.xaml
    /// </summary>
    public partial class InteractivePromptWindow : Window {
        public TransactionalTopLevel TopLevel { get; private set; }
        public GlyphPresenterTable Presenter { get; private set; }

        public InteractivePromptWindow () {
            InitializeComponent ();

            TopLevel = new TransactionalTopLevel ();
            Presenter = new GlyphPresenterTable (Resources);
            Presenter.Presenters.Add (new GlyphPresenter (new TypeSchemaObject<StructureObject> (), new StructurePresenter ()));
            Presenter.Presenters.Add (new GlyphPresenter (new TypeSchemaObject<Symbol> (), new SymbolPresenter ()));
            Presenter.Presenters.Add (new GlyphPresenter (new TypeSchemaObject<SetObject> (), new SetPresenter ()));
            Presenter.Presenters.Add (new GlyphPresenter (new TypeSchemaObject<IntegerObject> (), new IntegerPresenter ()));

            SourceText.Focus ();
        }

        public void AddResult (string source) {
            InteractiveResultGlyph prompt = new InteractiveResultGlyph (this, source);
            Panel.Children.Add (prompt);

            prompt.Evaluate ();

            SourceText.Focus ();
        }

        public void RemoveResult (InteractiveResultGlyph prompt) {
            Panel.Children.Remove (prompt);

            SourceText.Focus ();
        }

        private void SourceText_PreviewKeyDown (object sender, KeyEventArgs e) {
            if (e.Key == Key.Enter) {
                AddResult (SourceText.Text);
                SourceText.Text = "";
                e.Handled = true;
            }
        }

        public void Exit () {
            Close ();
        }

        private void StackPanel_MouseDown (object sender, MouseButtonEventArgs e) {
            SourceText.Focus ();
        }

        public AnyObject Evaluate (string source) {
            return TopLevel.Evaluate (source);
        }
    }
}
